package com.lazason.wib4android;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import weibo4andriod.ListObject;
import weibo4andriod.ListObjectWapper;
import weibo4andriod.Paging;
import weibo4andriod.Status;
import weibo4andriod.User;
import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

import com.lazason.wib4android.AsyncImageLoader.ImageCallback;
import com.lazason.wib4android.BasicWib.TimeLineTask;

public class HomeActivity extends BasicWib {

	String screen_name;
	Button other_weibo;

	String description;
	String location;
	String big_profile;
	boolean isNeedToUpdateProfile = true;
	TextView home_username;
	TextView description_text;
	TextView location_text;
	private LayoutInflater mInflater;
	ImageView home_profile;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		super.initActivity(savedInstanceState, R.layout.friend);
		// listView = (ListView) findViewById(android.R.id.list);
		mInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		LinearLayout header = (LinearLayout) mInflater.inflate(
				R.layout.home_header, null);
		home_username = (TextView) header.findViewById(R.id.home_username);
		description_text = (TextView) header.findViewById(R.id.description);
		location_text = (TextView) header.findViewById(R.id.location);
		other_weibo = (Button) header.findViewById(R.id.other_weibo_button);

		home_profile = (ImageView) header.findViewById(R.id.home_profile);

		big_profile = this.getIntent().getStringExtra("big_profile");
		if (big_profile != null) {
			loadProfile();
		}

		userId = this.getIntent().getStringExtra("id");
		description = this.getIntent().getStringExtra("description");
		description_text.setText(description);
		location = this.getIntent().getStringExtra("location");
		location_text.setText(location);

		screen_name = this.getIntent().getStringExtra("screen_name");

		if (screen_name == null) {
			if (this.getIntent().getData() != null) {
				screen_name = this.getIntent().getData().getQueryParameter(
						"screen_name");
			}
		}
		home_username.setText(screen_name);
		listView.addHeaderView(header);
		other_weibo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View paramView) {
				// TODO Auto-generated method stub

				Intent intent = new Intent();
				intent.putExtra("userId", screen_name);
				intent.setClass(HomeActivity.this, OtherWib.class);
				HomeActivity.this.startActivity(intent);
			}

		});

		adapter = new MyAdapter(HomeActivity.this, data, R.layout.listitem,
				new String[] { "profile", "weibo", "username", "picture",
						"retweetedText", "retweetedThumbnailPic", "created_at",
						"comment_repost" }, new int[] { R.id.profile,
						R.id.weibo, R.id.username, R.id.picture,
						R.id.retweetedText, R.id.retweetedThumbnailPic,
						R.id.createdTime, R.id.comment_repost }, listView);
		timeLineTask = new TimeLineTask();
		timeLineTask.execute(page);

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		if (MyApplication.friend != null) {
			adapter = new MyAdapter(this, data, R.layout.listitem,
					new String[] { "profile", "weibo", "username", "picture",
							"retweetedText", "retweetedThumbnailPic",
							"created_at" }, new int[] { R.id.profile,
							R.id.weibo, R.id.username, R.id.picture,
							R.id.retweetedText, R.id.retweetedThumbnailPic,
							R.id.createdTime }, listView);
			int lastItem = listView.getFirstVisiblePosition();

			listView.setAdapter(adapter);
			listView.setSelection(lastItem);
		}
		super.onResume();
	}

	protected void loadProfile() {
		Drawable cachedImage = asyncImageLoader.loadDrawable(this, big_profile,
				"bf" + big_profile.hashCode(), Thread.MAX_PRIORITY,
				new ImageCallback() {
					public void imageLoaded(Drawable imageDrawable,
							String imageUrl, String id) {

						if (home_profile != null && imageDrawable != null) { // 防止图片url获取不到图片是，占位图片不见了的情况
							home_profile.setImageDrawable(imageDrawable);

						}
					}
				});

		if (cachedImage == null) {
			// holder.profile.setImageResource(R.drawable.icon);
			home_profile.setImageDrawable(null);
		} else {
			home_profile.setImageDrawable(cachedImage);
		}
	}

	@Override
	protected void addData(List list) {
		for (Object status : list) {
			if (status instanceof Status) {
				Map<String, Object> map = Util.status2Map((Status) status);
				if (isNeedToUpdateProfile) {
					if (big_profile == null) {
						big_profile = ((String) map.get("profile")).replace(
								"/50/", "/180/");
						loadProfile();
						screen_name = (String) map.get("username");
						home_username.setText(screen_name);
						description = (String) map.get("description");
						description_text.setText(description);
						location = (String) map.get("location");
						location_text.setText(location);
					}
					isNeedToUpdateProfile = false;
				}
				data.add(map);
			}

		}

	}

	@Override
	protected List readTimeline(int arg) throws WeiboException {
		List timeLine = new ArrayList();
		if (userId != null) {

			timeLine = weibo.getUserTimeline(userId, new Paging(arg));
		} else if (screen_name != null) {
			timeLine = weibo.getUserTimeline("screen_name="
					+ URLEncoder.encode(screen_name), new Paging(arg), true);
		} else {
			timeLine = weibo.getUserTimeline(new Paging(arg));
			if (timeLine != null) {
				if (timeLine.size() > 0) {
					Status status = (Status)(timeLine.get(0));
					screen_name = status.getUser().getName();
					userId = String.valueOf(status.getUser().getId());
					ListObjectWapper wapper = weibo.getUserLists(userId,
							true);
					List<ListObject> lists = wapper.getListObjects();
					for (ListObject listObject : lists) {
						Log.d(this.getClass().getName(),listObject.toString());
					}
					List<Status> statuses = weibo.getListStatuses(userId, "231101130036069903", true);
					for (Status status1 : statuses) {
						Log.d(this.getClass().getName(),status1.toString());
					} 
				}
			}
		}
		if (timeLine == null || timeLine.size() == 0) {
			timeLine = weibo.getUserTimeline("screen_name="
					+ URLEncoder.encode(screen_name), new Paging(arg), true);
		}
		if (timeLine == null || timeLine.size() == 0) {

			String s;
			try {
				s = java.net.URLEncoder.encode(screen_name, "utf-8");
				Log.d(this.getClass().getName(), " weibo.showUser(s,true) ");
				User user = weibo.showUser(s, true);
				Log.d(this.getClass().getName(), "user id: " + user.getId());
				Log.d(this.getClass().getName(), "user name: " + user.getName());
				userId = String.valueOf(user.getId());
				timeLine = weibo.getUserTimeline(userId, new Paging(arg));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return timeLine;
	}

	@Override
	void refresh() {
		// TODO Auto-generated method stub
		
	}
}
